<template>
	<div>
		<el-row class="tac">
			<el-col :span="4">
				<div class="setheight_scroller">
						<div>
							<h4>CMD权限名称</h4>
							<el-button type="text" @click="AddCmdTree">添加权限</el-button>
							<el-button type="text" @click="DelCmdTree">删除权限</el-button>
						</div>
						<br />
						<el-tree class="filter-tree " :data="CmdTreeData" :props="defaultProps" node-key="id" :expand-on-click-node="false" @current-change="handleClick" default-expand-all ref="tree">
						</el-tree>
				</div>
			</el-col>

			<el-col :span="20">
				<el-row>
					<el-col :span="8">
						<el-input placeholder="请输入权限ID或名称" v-model="p_cmd_id">
							<template slot="prepend">CMD权限:</template>
						</el-input>
					</el-col>
					<el-col :span="16">
						<el-button type="primary" @click="showdata">查询</el-button>
						<el-button type="primary" @click="showAdd">增加</el-button>
						<el-button type="primary" @click="showDel">删除</el-button>
						<el-button type="primary" @click="showAllocation">分配</el-button>
						<el-button type="primary" @click="showExport">导出</el-button>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span='24'>
						<el-card class="box-card" style="height: 800px;">
							<div class="setheight_scroller">
								<el-row>
									<div style="font-weight:bold;font-size: 20px;">{{treemsg}} </div>
								</el-row>
								<el-table width='100%' :data="CmdData.slice((currentPage-1)*pagesize,currentPage*pagesize)" showOverflowTooltip style="width: 100%" stripe border tooltip-effect="dark" ref="multipleTable" @selection-change="handleSelectionChange" @row-click="rowClick">
									<el-table-column type="selection" width="50"> </el-table-column>
									<el-table-column  prop="cmd_id" label="cmdID" show-overflow-tooltip></el-table-column>
									<el-table-column prop="cmd_name" label="cmd名称" show-overflow-tooltip></el-table-column>
									<el-table-column prop="cmd_power_id" label="权限id" show-overflow-tooltip></el-table-column>
									<el-table-column label="内容" prop="content" show-overflow-tooltip>
										<template slot-scope="scope">
											<a href="javascript:;" @click="show_article(scope.$index, scope.row)" class="buttonText">{{scope.row.content}}</a>
										</template>
									</el-table-column>

									<el-table-column prop="name" label="描述" width="70"></el-table-column>
									<el-table-column label="操作" width="250">
										<template slot-scope="scope">
											<i class="el-icon-edit" @click="showEdit(scope.$index, scope.row)">修改</i>
											<router-link :to="{path: '/knowledge/knowledgeAdd', query: {power_key:scope.row.cmd_key}}">
												<i class="el-icon-edit"> 内容链接  </i>
											</router-link>
										</template>
									</el-table-column>
								</el-table>
								<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="this.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="this.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="CmdData.length">
								</el-pagination>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</el-col>
		</el-row>

		<!--新增界面-->
		<el-dialog :title="text" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')" style="padding-bottom:0;">
			<el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm" style="height:240px;">
				<el-form-item label="cmdID" prop="cmd_id">
					<el-input v-model="addForm.cmd_id" auto-complete="off" placeholder="请输入cmdID"></el-input>
				</el-form-item>
				<el-form-item label="cmd名称" prop="cmd_name">
					<el-input v-model="addForm.cmd_name" auto-complete="off" placeholder="请输入cmd名称"></el-input>
				</el-form-item><br />
				
				<el-form-item label="权限" prop="cmd_filename">
					<el-select v-model="addForm.cmd_filename" placeholder="请选择" filterable style='width:100%'>
						<el-option v-for="item in cmd_power_data" :key="item.power_id" :label='item.power_name' :value="item.power_id">
						</el-option>
					</el-select>
					
				</el-form-item>
				<el-form-item label="描述" prop="remarks">
					<el-input type="textarea" placeholder="请输入描述" auto-complete="off" :rows="4" v-model="addForm.remarks"></el-input>
				</el-form-item>
			</el-form>
			<br /><br />
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
				<el-button @click="reset()">重置</el-button>
			</div>
		</el-dialog>

		<!--新增权限   @close="resetForm('addForm')"-->
		<el-dialog :title="text" :visible.sync="PowerTreeVisible" :close-on-click-modal="false" style="padding-bottom:0;">
			<el-form :model="addCmdTreeForm" label-width="120px" :rules="addPowerTreeRules" ref="addCmdTreeForm" style="height:240px;">
				<el-form-item label="cmd权限名称" prop="tree_name">
					<el-input v-model="addCmdTreeForm.tree_name" auto-complete="off" placeholder="请输入权限名称"></el-input>
				</el-form-item>
				<el-form-item label="上级权限">
					<el-cascader placeholder="" :options="CmdTreeData" filterable change-on-select :props="defaultCascader" clearable v-model='selectFatherKey'></el-cascader>
				</el-form-item>
				<el-form-item label="显示顺序" prop="displayindex">
					<el-input v-model="addCmdTreeForm.displayindex" auto-complete="off" placeholder="请输入显示顺序"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addPowerTreeSubmit">提交</el-button>
				<el-button @click="resetFormregion()">重置</el-button>
			</div>
		</el-dialog>

		<!--分配权限管理-->
		<el-dialog title="分配权限" :visible.sync="addPowerVisible" width="30%" >
			<span>选择权限</span>
					<el-select clearable v-model="cmd_privilege" placeholder="请选择" filterable style='width:100%'>
						<el-option v-for="item in cmd_power_data" :key="item.power_id" :label='item.power_name' :value="item.power_id">
						</el-option>
					</el-select>
			<span slot="footer" class="dialog-footer">
			    <el-button @click="addPowerVisible = false;">取 消</el-button>
			    <el-button type="primary" @click="Allocation_permissions">确 定</el-button>
			  </span>
		</el-dialog>

		<el-dialog title="文章详情" :visible.sync="showVisible">
			<mavon-editor v-model="testValue" style="height: 100%" ref="md" :toolbarsFlag="false" :subfield="false" defaultOpen="preview"></mavon-editor>
			<br />
			<span slot="footer" class="dialog-footer">
			    <el-button @click="showVisible = false;">关闭</el-button>
			 </span>
		</el-dialog>
	</div>
</template>

<script>
	import { query, apiparas, execute } from '../../api/api';
	import { Cookie, Client } from '../../js/common';
	export default {
		data() {
			return {
				cmd_privilege:'',
				cmd_key:'',
				cmd_id:'',
				cmd_power_data:'',
				CmdTreeData: [],
				selectFatherKey: [],
				multipleTablePower1: [],
				currentPage: 1,
				pagesize: 10,
				CmdData: [],
				treemsg: '',
				p_cmd_id: '',
				text: '',
				multipleTablePower: [],
				powerid: '',
				power_key: '',
				selectRow: {},
				multipleTable: [],
				testValue: '',
				addPowerVisible: false,
				addFormVisible: false,
				showVisible: false,
				defaultCascader: {
					value: 'id',
					children: 'subs',
					label: 'tree_name'
				},
				defaultProps: {
					id: 'id',children: 'subs',label: 'tree_name'
				},
				addCmdTreeForm: {
					tree_name: '',
					displayindex: '',
				},
				addForm: {
					cmd_filename:'',
					cmd_id: '',
					cmd_name: '',
					classify: '',
					remarks: '',
				},
				row_tree_name:"",
				PowerTreeVisible: false,
				showknowledge: {}, //选择浏览得知识对象
				isEditShow: false,
				addPowerTreeRules: {
					tree_name: [{
						required: true,message: '请输入权限名称',trigger: 'blur'
					}, ],
					displayindex: [{
						required: true,message: '请输入显示顺序',trigger: 'blur'
					}, ]
				},
				addFormRules: {
					power_id: [{
						required: true,message: '请输入权限ID',trigger: 'blur'
					}, ],
					power_name: [{
						required: true,message: '请输入权限名称',trigger: 'blur'
					}, ],
					classify: [{
						required: true,message: '请输入分类',trigger: 'blur'
					}, ]
				},
			}
		},
		methods: { //函数
			handleSelectionChange(val) {
				this.multipleTable = val;
				this.multipleTablePower = this.multipleTable;
			},
			rowClick(row, event, column) {
				this.power_key = row.power_key;
				this.toggleSelection(row);
			},
			toggleSelection(rows) {
				 if (this.multipleTable.length>0) {
			        this.$refs.multipleTable.clearSelection();
			    } 
			    this.$refs.multipleTable.toggleRowSelection(rows);
			},
			resetFormregion() {
				this.addCmdTreeForm.tree_name = '',
				this.addCmdTreeForm.displayindex = ''
			},
			reset: function() { //重置
				if(this.isEditShow) {
					this.addForm.power_id = this.selectRow.power_id;
					this.addForm.power_name = this.selectRow.power_name;
					this.addForm.classify = this.selectRow.classify;
					this.addForm.remarks = this.selectRow.remarks;
				} else {
					this.addForm = {
						power_id: '',
						power_name: '',
						classify: '',
						remarks: ''
					};
				}
			},
			resetForm: function(formName) { //重置
				this.$refs[formName].resetFields();
			},

			//分配权限角色
			showAllocation() {
				this.cmd_privilege='';
				this.multipleTablePower1 = this.multipleTablePower
				this.addPowerVisible = true;
			},
			//增加权限节点树
			AddCmdTree() {
				this.PowerTreeVisible = true;
				this.text = '新增';
				this.selectFatherKey = [];
				this.addCmdTreeForm = {
					tree_name: '',
					displayindex: '',
				}
			},
			//删除权限节点树
			DelCmdTree() {
				this.$confirm('是否确定删除'+this.row_tree_name+'权限?', '提示', {
					confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'
				}).then(() => {
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'cmd_tree_key', this.powerid);
				let _paras = apiparas.getParas('default', 'basic|del_cmd_tree', jsonparas);
				execute(_paras).then(response => {
					if(response.errid == 0) {
						this.showPowerTreeData();
						this.addFormVisible = false;
						this.showdata();
						this.$message({
							showClose: true,
							message: '成功删除',
							type: 'success'
						});
					} else {
						this.$message({
							showClose: true,
							message: response.errmsg,
							type: response.errmsg
						});
					}
				});
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消删除'
					});
				});
			},
			showdata: function() { //查询数据
				//显示数据
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'cmd_tree_key', this.powerid);
				apiparas.pushPara(jsonparas, 'cmd', this.p_cmd_id);
				apiparas.pushPara(jsonparas, 'classify', '10003');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_cmd', jsonparas);
				query(_paras).then(response => {
					var json_data = response.result;
					this.CmdData = json_data;
				});
			},
			//点击权限树节点时候触发的事件
			handleClick(row) {
				this.row_tree_name=row.tree_name;
				this.treemsg = row.tree_name;
				this.powerid = row.id;
				this.showdata();
			},
			//获取权限树节点数据
			showPowerTreeData() {
				//显示数据
				let jsonparas = [];
				let paras = apiparas.getParas_rtype('default', 'basic|get_cmd_tree', 3, jsonparas);
				query(paras).then(response => {
					var json_data = response.result;
					this.CmdTreeData = json_data;
				});
			},
			//增加角色
			Allocation_permissions() {
				var keys = '';
				for(var i = 0; i < this.multipleTablePower1.length; i++) {
					keys += this.multipleTablePower1[i]['cmd_key'] + ",";
				}
				keys = keys.substring(0, keys.length - 1);
				if(keys == '') {
					this.$notify({
						title: '信息提示',
						message: '请选择要为那个权限添加角色！',
						type: 'info'
					});
					return;
				}
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'cmd_power_id', this.cmd_privilege);
				apiparas.pushPara(jsonparas, 'cmd_key', keys);
				let _paras = apiparas.getParas('default', 'basic|update_cmd_power_id', jsonparas);
				execute(_paras).then(response => {
					this.addPowerVisible = false;
					if(response.errid == 0) {
						this.showdata();
						this.$message({
							showClose: true,
							message: '成功添加',
							type: 'success'
						});
					} else {
						this.$message({
							showClose: true,
							message: '添加失败',
							type: response.errmsg
						});
					}
				});
			},

			get_cmd_power: function() {
				let jsonparas = [];
				let _paras = apiparas.getParas('default', 'basic|get_cmd_power', jsonparas);
				query(_paras).then(response => {
					this.cmd_power_data = response.result;
				});
			},
			
			//新增
			showAdd: function() { //显示新增对话框
				this.addFormVisible = true;
				this.text = '新增';
				this.isEditShow = false;
				this.addForm = {
					power_id: '',
					power_name: '',
					classify:'',
					remarks: ''
				};
			},

			//编辑
			showEdit: function(index, row) {
				this.cmd_key=row.cmd_key;
				this.addForm.cmd_id=row.cmd_id;
				this.addForm.cmd_filename=row.cmd_power_id;
				this.addForm.cmd_name=row.cmd_name;
				this.addForm.classify=row.classify;
				this.addFormVisible = true;
				this.text = '编辑';
				this.selectRow = row;
				this.addForm.remarks = row.remarks;
				this.isEditShow = true;
			},

			//增加权限树节点
			addPowerTreeSubmit() {
				let fatherKey = this.selectFatherKey.pop();
				if(fatherKey === undefined) {
					fatherKey = 0;
				}
				//增加条件
				let jsonparas = [
				{'name': 'father_key','value': fatherKey},
				{'name': 'tree_name','value': this.addCmdTreeForm.tree_name},
				{'name': 'displayindex','value': this.addCmdTreeForm.displayindex}
				];
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|insert_cmd_tree', jsonparas);
				execute(_paras).then(response => {
					if(response.errid == 0) {
						this.PowerTreeVisible = false;
						this.showPowerTreeData();
						this.$message({
							showClose: true,message: '添加成功',type: 'success'
						});
					} else {
						this.$message({
							showClose: true,message: response.errmsg,type: 'error'
						});
					}
				});
			},
			addSubmit: function() { //提交
				if(this.isEditShow) {
					//增加查询条件
					let jsonparas = [
					{'name': 'cmd_key','value': this.cmd_key},
					{'name': 'cmd_id','value': this.addForm.cmd_id},
					{'name': 'cmd_name','value': this.addForm.cmd_name},
					{'name': 'classify','value': this.addForm.classify},
					{'name': 'remarks','value': this.addForm.remarks},
					{'name': 'cmd_power_id','value': this.addForm.cmd_filename}
					]
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|update_cmd', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.addFormVisible = false;
							this.$message({
								showClose: true,message: '修改成功',type: 'success'
							});
							this.showdata();
						} else {
							this.$message({
								showClose: true,message: response.errmsg,type: 'error'
							});
						}
					});
				} else {
					//处理添加
					var jsonparas = [];
					//增加查询条件
					let jsonparas = [
					{'name': 'cmd_id','value': this.addForm.cmd_id},
					{'name': 'cmd_tree_key','value': this.powerid},
					{'name': 'cmd_power_id','value': this.addForm.cmd_filename},
					{'name': 'cmd_name','value': this.addForm.cmd_name},
					{'name': 'classify','value': '10003'},
					{'name': 'remarks','value': this.addForm.remarks}
					]
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|insert_cmd', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.showdata();
							this.addFormVisible = false;
							this.$message({
								showClose: true,message: '成功添加',type: 'success'
							});
						} else {
							this.$message({
								showClose: true,message: response.errmsg,type: 'error'
							});
						}
					});
				}
			},
			//删除
			showDel: function() {
				var keys = '';
				for(var i = 0; i < this.multipleTablePower.length; i++) {
					keys += this.multipleTablePower[i].cmd_key + ",";
				}
				if(keys == '') {
					this.$notify({
						title: '信息提示',message: '请选择要删除的明细！',type: 'info'
					});
					return;
				}
				keys = keys.substring(0, keys.length - 1);
				this.$confirm('此操作将永久删除选中的权限, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let jsonparas = [];
					apiparas.pushPara(jsonparas, 'keys', keys);
					let _paras = apiparas.getParas('default', 'basic|del_cmd', jsonparas);
					execute(_paras).then(response => {
						let json_data = response.result;
						if(response.errid == 0) {
							this.$message({
								showClose: true,message: '成功删除选中的数据',type: 'success'
							});
							this.showdata();
						} else {
							this.$message({
								showClose: true,message: response.errmsg,type: 'error'
							});
						}
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			showExport: function() //导出
			{
				this.downloadLoading = true
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('@../../vendor/Export2Excel')
					const tHeader = ['cmdID', 'cmd名称','权限id','内容', '分类', '描述', '创建时间', '修改时间'];
					const filterVal = ['cmd_id', 'cmd_name', 'cmd_power_id', 'content','name','remarks', 'create_time', 'update_time'];
					const list = this.CmdData;
					const _data = this.formatJson(filterVal, list);
					export_json_to_excel(tHeader, _data, 'CMD权限','CMD权限');
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			tableRowClassName(row, rowIndex) {
				return '';
			},
			handleSizeChange: function(size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage;
			},
			show_article: function(index, row) {
				this.showVisible = true;
				this.showknowledge = row;
				let _this = this;
				let fileName = row.content;
				let client = Client.NewOSS();
				async function getBuffer() {
					try {
						let result = await client.get(fileName);
						_this.testValue = result.content.toString()
					} catch(e) {
						console.log(e);
					}
				}
				getBuffer();
			},
		},
		created: function() {
			this.get_cmd_power();
			this.showPowerTreeData();
		}
	}
</script>

<style>
	.setheight_scroller {
		height: 790px;
		overflow: auto;
	}
</style>